package com.ztom.offer.v2;

/**
 * 机器人的运动范围
 * <p>
 * https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/
 *
 * @author ZhangTao
 */
public class Code11MovingCount {

    int count = 0;

    public int movingCount(int m, int n, int k) {
        boolean[][] visited = new boolean[m][n];
        dfs(m, n, 0, 0, k, visited);
        return count;
    }

    private void dfs(int m, int n, int i, int j, int k, boolean[][] visited) {
        if (i < 0 || i >= m || j < 0 || j >= n) {
            return;
        }
        if (visited[i][j]) {
            return;
        }
        visited[i][j] = true;
//        int c = bitSum(i) + bitSum(j);
        int c = i / 10 + i % 10 + j / 10 + j % 10;
        if (c > k) {
            return;
        }
        count++;
        dfs(m, n, i + 1, j, k, visited);
        dfs(m, n, i - 1, j, k, visited);
        dfs(m, n, i, j + 1, k, visited);
        dfs(m, n, i, j - 1, k, visited);
    }

    private int bitSum(int x){
        int sum = 0;
        while(x != 0){
            sum += x % 10;
            x /= 10;
        }
        return sum;
    }
}
